from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.shortcuts import redirect
from django.contrib import messages
from .models import Station, Pile, Order
from .connectors import connect_pile, disconnect_pile
from simpleui.admin import AjaxAdmin
from django.http import JsonResponse

@admin.register(Station)
class StationAdmin(admin.ModelAdmin):
    list_display = ('name', 'did', 'host', 'port', 'created_at')
    search_fields = ('name', 'did')
    list_filter = ('created_at',)
    ordering = ('-created_at',)

@admin.register(Pile)
class PileAdmin(AjaxAdmin):
    list_display = ('number', 'station', 'gun_count', 'logged_in','vin','connection_actions')
    readonly_fields = ('logged_in',)
    list_filter = ('station', 'logged_in')
    search_fields = ('number',)
    ordering = ('-created_at',)

    actions = ('show_documentation',)
    def show_documentation(self, request, queryset):
        # 直接显示文档内容，无需选中数据验证
        return JsonResponse({
            "msg": "请正确按照说明设置，否则无法连接服务器",
            "time": 5000,        # 3秒后关闭弹窗
            "status": "success"  # 自定义状态码
        })
    show_documentation.short_description = '云快充桩设置说明'
    show_documentation.type = 'info'
    show_documentation.icon = 'el-icon-document'

    # 关键设置：使按钮始终可用（即使未选中数据）
    show_documentation.enable = True
    # 文档弹窗配置
    show_documentation.ignore_model_operations = True
    show_documentation.layer = {
        'title': '云快充桩设置说明',
        'tips': '模拟桩请在电桩管理模块设置协议为云快充协议，公钥和私钥如下-----------------'
                '公钥：MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOAs2WCYhYxClvQv2+hDYCPiEh3jB7a+HNIu7pqcwbm886R5yQhJ0rqfVMeQYnherL9uMgr7ID2AaJXhl7qb6C8CAwEAAQ=='
                '私钥：MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA4CzZYJiFjEKW9C/b6ENgI+ISHeMHtr4c0i7umpzBubzzpHnJCEnSup9Ux5BieF6sv24yCvsgPYBoleGXupvoLwIDAQABAkEAnFMKHw8dCcshwxRgsF3TfBJY+dhod6mpJXSu1Mh9W0w3I/krfPzHoXadk8FrzFUTOnKx+CtEBQtS+CrhkdjJ6QIhAPKM5k6C+u9JJ5H+lPSNXzIyEp+AXgEXcvqGhvcgyaVlAiEA7JsbLllSmr5zGaADCITHuPq5bOTIJv6qXXQ5LnavmAMCIQDLLuUvF+IF2Y5gapd1VYhNkEyxeONGntIes9sT4k+JUQIgeI3PG56HaDEBlFzjLsP4v1eAgutO0A+R3mwJdpMihOECIQC3xEhZtAleaqF29d4zTtDNHTuHncCYGgKIZ2Jntq5OwQ==',

        # 移除确认按钮，只保留关闭按钮
        'confirm_button': "确定",
        'cancel_button': "我已知晓",
        'width': '40%',
        'labelWidth': "80px",
        'params': []
    }

    def connection_actions(self, obj):
        return format_html(
            '<div style="display: flex; gap: 8px; align-items: center;">'  # 添加容器设置间距
        '<a class="default" href="{}" style="margin-right: 10px;">连接</a>'
        '<a class="deletelink" href="{}">断开</a>'
        '<a class="default" href="{}" style="padding: 5px 10px; border-radius: 3px; color: #000; text-decoration: none;">查看枪状态</a>'
        '</div>',
            reverse('iot:connect_pile', args=[obj.pk]),
            reverse('iot:disconnect_pile', args=[obj.pk]),
            reverse('iot:manage_gun_status', args=[obj.pk])  # 新增
        )

    connection_actions.short_description = '操作'

    # 新增方法：处理枪状态视图
    def change_view(self, request, object_id, form_url='', extra_context=None):
        # 如果请求中包含创建枪状态的操作
        if '_create_guns' in request.POST:
            pile = self.get_object(request, object_id)
            pile.create_gun_statuses()
            self.message_user(request, '枪状态已创建', messages.SUCCESS)
            return redirect('manage_gun_status', pile_id=object_id)

        return super().change_view(request, object_id, form_url, extra_context)

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('order_sn', 'pile', 'gun_id', 'status', 'energy', 'total_cost', 'start_time', 'end_time')
    list_filter = ('status', 'pile', 'gun_id')
    search_fields = ('order_sn',)
    readonly_fields = ('start_time', 'end_time')
    ordering = ('-created_at',)

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('station', 'pile')